package com.zh.common.mybatis.plugin;

import com.zh.common.datasource.RoutingDataSourceHolder;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Properties;

@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class RoutingDatasourcePlugin implements Interceptor {
    private static Logger logger = LoggerFactory.getLogger(RoutingDatasourcePlugin.class);
    /**
     * 插件方法更新
     */
    private static final String UPDATE = "update";

    /**
     * 插件方法查询
     */
    private static final String QUERY = "query";

    public RoutingDatasourcePlugin() {
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
        try {
            if (!synchronizationActive) {
                String methodName = invocation.getMethod().getName();
                if (QUERY.equals(methodName)) {
                    RoutingDataSourceHolder.putSlaveDataSource();
                    if (logger.isDebugEnabled()) {
                        logger.debug("未开启事务，QUERY语句，Plugin切换数据源至" + RoutingDataSourceHolder.getDataSource());
                    }
                } else if (UPDATE.equals(methodName)) {
                    RoutingDataSourceHolder.putMasterDataSource();
                    if (logger.isDebugEnabled()) {
                        logger.debug("未开启事务，UPDATE语句，Plugin切换数据源至" + RoutingDataSourceHolder.getDataSource());
                    }
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("开启事务，Plugin不再切换数据源");
                }
            }
            return invocation.proceed();
        } finally {
            if (!synchronizationActive) {
                RoutingDataSourceHolder.clearDataSource();
            }
        }

    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        //
    }
}
